/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.util;

import com.jspx.boot.EnvFactory;
import com.jspx.boot.environment.Environment;
import com.jspx.boot.environment.EnvironmentTemplate;
import com.jspx.boot.sign.SafetyLevel;
import com.jspx.txweb.dispatcher.Dispatcher;
import com.jspx.utils.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by IntelliJ IDEA.
 * User:chenYuan (mail:39793751@qq.com)
 * Date: 2004-4-5
 * Time: 11:31:26
 * HttpServletRequest,HttpServletRequest cookie 扩展类
 */

public class RequestUtil {
    final public static String requestUserAgent = "User-Agent";
    final public static String requestAcceptLanguage = "Accept-Language";
    final public static String requestReferer = "Referer";
    final public static String requestAcceptRanges = "Accept-Ranges";
    final public static String requestContentLength = "Content-Length";
    final public static String requestContentRange = "Content-Range";
    final public static String requestContentType = "Content-Type";
    final public static String requestContentDisposition = "Content-Disposition";

    //微信小程序
    final public static String Browser_miniprogram = "miniprogram";
    //微信浏览器
    final public static String Browser_micromessenger = "micromessenger";

    private static EnvironmentTemplate envTemplate = EnvFactory.getEnvironmentTemplate();
    private static boolean repairEncode = envTemplate.getBoolean(Environment.repairEncode);
    private static String repairRequestMethod = envTemplate.getString(Environment.repairRequestMethod, "*");
    private static final String[] mobileKeywords = new String[]{"mobile",
            "android", "symbianos", "iphone", "wp\\d*", "windows phone", "mqqbrowser", "nokia", "midp-2", "untrusted/1.0", "windows ce", "blackberry", "ucweb", "brew", "j2me", "yulong",
            "coolpad", "tianyu", "ty-", "k-touch", "haier", "dopod", "lenovo", "huaqin", "aigo-", "ctc/1.0", "ctc/2.0", "cmcc", "daxian", "mot-", "sonyericsson", "gionee", "htc",
            "zte", "lg", "sony", "samsung", "sharp", "huawei", "webos", "gobrowser","khtml", "ucbrowser", "iemobile", "operamobi", "opera mobi", "wap2.0", "wapi", "openwave", "nexusone"};

    public static final Map<String, String> systemKeywords = new LinkedHashMap<String, String>();

    public static final Map<String, String> browserKeywords = new LinkedHashMap<String, String>();

    final public static int paramMaxLength = 50000;
    static {
        systemKeywords.put("android", "Android");
        systemKeywords.put("nt4", "Windows NT4");
        systemKeywords.put("unix", "Unix");
        systemKeywords.put("windows 98", "Windows 98");
        systemKeywords.put("nt 5.0", "Windows 2000");
        systemKeywords.put("nt 5.1", "Windows XP");
        systemKeywords.put("nt 5.2", "Windows 2003");
        systemKeywords.put("nt 6.0", "Windows 2008");
        systemKeywords.put("nt 6.1", "Windows 7");
        systemKeywords.put("nt 6.2", "Windows 8");
        systemKeywords.put("vista", "Windows vista");
        systemKeywords.put("nt 10.0", "Windows 10");
        systemKeywords.put("nt 11", "Windows 11");
        systemKeywords.put("nt 12", "Windows 12");
        systemKeywords.put("iphone os", "iPhone OS");
        systemKeywords.put("mac os", "Mac OS");
        systemKeywords.put("tel", "Telport");
        systemKeywords.put("linux", "Linux");
        systemKeywords.put("sunos", "SunOS");
        //--------------------------------------------------------------------------------------------------------------
        browserKeywords.put("micromessenger", "MicroMessenger"); //微信
        browserKeywords.put("miniprogram", "miniprogram"); //微信 小程序

        browserKeywords.put("netcaptor", "NetCaptor");
        browserKeywords.put("mozilla", "Mozilla");
        browserKeywords.put("myie", "MyIe");
        browserKeywords.put("myie2", "MyIE2");
        browserKeywords.put("maxthon", "Maxthon");
        browserKeywords.put("firefox", "Firefox");
        browserKeywords.put("msie 5.5", "Internet Explorer 5.5");
        browserKeywords.put("msie 6.0", "Internet Explorer 6.0");
        browserKeywords.put("msie 7.0", "Internet Explorer 7.0");
        browserKeywords.put("msie 8.0", "Internet Explorer 8.0");
        browserKeywords.put("msie 9.0", "Internet Explorer 9.0");
        browserKeywords.put("msie 10.0", "Internet Explorer 10.0");
        browserKeywords.put("msie 11.0", "Internet Explorer 11.0");
        browserKeywords.put("msie 12.0", "Internet Explorer 12.0");
        browserKeywords.put("msie 13.0", "Internet Explorer 13.0");
        browserKeywords.put("msie 14.0", "Internet Explorer 14.0");
        browserKeywords.put("msie 15.0", "Internet Explorer 15.0");
        browserKeywords.put("msie 15.0", "Internet Explorer 15.0");
        browserKeywords.put("msie", "Internet Explorer");
        browserKeywords.put("chrome", "Chrome");
        browserKeywords.put("safari", "Safari");
        browserKeywords.put("opera", "Opera");
        browserKeywords.put("360", "360 Browser");
        browserKeywords.put("mqqbrowser", "MQQBrowser");
        browserKeywords.put("qqbrowser", "QQBrowser");
        browserKeywords.put("googlebot", "Google Spider"); //网络爬虫
        browserKeywords.put("baiduspider", "Baidu Spider"); //网络爬虫
        browserKeywords.put("yahoo! slurp", "YaHoo Spider"); //雅虎 网络爬虫
        browserKeywords.put("msnbot", "MSN Spider"); //网络爬虫
        browserKeywords.put("sosospider", "SoSo Spider"); //网络爬虫
        browserKeywords.put("yodaobot", "YouDao Spider"); //搜搜 网络爬虫
        browserKeywords.put("yodaobot", "YouDao Spider"); //有道 网络爬虫
        browserKeywords.put("sogou", "Sogou Spider"); //搜狗 网络爬虫
        browserKeywords.put("fast-webcrawler", "Alltheweb Spider"); //网络爬虫
        browserKeywords.put("lycos_spider", "Lycos Spider"); //网络爬虫
        browserKeywords.put("inktomi", "Inktomi Spider"); //网络爬虫
        browserKeywords.put("Java", "Java Server"); //网络爬虫
        browserKeywords.put("download", "Download Application"); //网络爬虫
    }


    private RequestUtil() {

    }

    /**
     * @param request 请求   请求方式为自定义的       X-Requested-With=roc
     * @return 判断是否为ROC请求
     */
    public static boolean isRocRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        return requestedWith != null && requestedWith.toLowerCase().contains("roc");
    }

    /**
     * @param request 请求
     * @return 判断是否为盗用
     */
    public static boolean isPirated(HttpServletRequest request) {
        if (request == null) return false;
        String serverName = URLUtil.getTopDomain(request.getServerName());
        if (serverName == null) return false;
        String referer = request.getHeader(requestReferer);
        if (!StringUtil.hasLength(referer)) return false;
        //排除二级域名
        return !serverName.equalsIgnoreCase(URLUtil.getTopDomain(referer));
    }

    public static boolean isMultipart(HttpServletRequest request) {
        if (request == null) return false;
        String type = null;
        String type1 = request.getHeader(requestContentType);
        String type2 = request.getContentType();
        if (type1 == null && type2 != null) {
            type = type2;
        } else if (type2 == null && type1 != null) {
            type = type1;
        } else if (type1 != null) {
            type = (type1.length() > type2.length() ? type1 : type2);
        }
        if (type == null) {
            type = request.getHeader(requestContentType);
        }
        if (type == null) {
            return false;
        } else if (type.toLowerCase().startsWith("multipart")) {
            return true;
        }
        return false;
    }

    /**
     * @param response 应答
     * @return 参数列表
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getResponseMap(HttpServletResponse response) {
        if (response == null) return new HashMap(0);
        Map<String, Object> result = new HashMap();
        result.put("bufferSize", response.getBufferSize());
        result.put("characterEncoding", response.getCharacterEncoding());
        result.put("bufferSize", response.getBufferSize());
        result.put("locale", response.getLocale());
        return result;
    }


    /**
     * @param request 请求
     * @return 参数map, 不错误默认页面执行过程，只在传递参数的时候使用,这样能提高速度
     * @throws Exception 异常
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getRequestMap(HttpServletRequest request) throws Exception {
        Map result = new RequestMap(request);
        if (request == null || isRocRequest(request)) return result;
        Enumeration enu = (Enumeration) BeanUtil.getProperty(request, "getParameterNames");
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            Object values = BeanUtil.getProperty(request, "getParameterValues", new Object[]{name},false);
            if (values != null && values.getClass().isArray() && ArrayUtil.getLength(values) > 1) {
                if (repairEncode && (repairRequestMethod.equals("*") || StringUtil.indexIgnoreCaseOf(repairRequestMethod, request.getMethod()) != -1)) {
                    int max = ArrayUtil.getLength(values);
                    String[] tempArray = new String[max];
                    for (int i = 0; i < max; i++) {
                        Object o = Array.get(values, i);
                        if (o != null)
                            tempArray[i] = new String(((String) o).getBytes("ISO-8859-1"), Dispatcher.getEncode());
                    }
                    result.put(name, tempArray);
                } else
                    result.put(name, values);
            } else {
                result.put(name, getString(request, name, false));
            }
        }
        return result;
    }


    /**
     * @param request    请求
     * @param name       命令名称
     * @param defaultVal 默认
     * @return 变量
     */
    public static int getInt(HttpServletRequest request, String name, int defaultVal) {
        String value = getString(request, name, true);
        if (StringUtil.isNULL(value)) return defaultVal;
        return StringUtil.toInt(value);
    }

    /**
     * @param request 请求
     * @param name    命令名称
     * @return 变量
     */
    public static int getInt(HttpServletRequest request, String name) {
        return StringUtil.toInt(getString(request, name, true));
    }

    /**
     * @param request    请求
     * @param name       命令名称
     * @param defaultVal 默认
     * @return 变量
     */
    public static long getLong(HttpServletRequest request, String name, long defaultVal) {
        String value = getString(request, name, true);
        if (StringUtil.isNULL(value)) return defaultVal;
        return StringUtil.toLong(value);
    }

    /**
     * @param request 请求
     * @param name    命令名称
     * @return 变量
     */
    public static long getLong(HttpServletRequest request, String name) {
        return getLong(request, name, 0);
    }

    /**
     * @param request    请求
     * @param name       命令名称
     * @param defaultVal 默认
     * @return 变量
     */
    public static float getFloat(HttpServletRequest request, String name, float defaultVal) {
        String value = getString(request, name, true);
        if (StringUtil.isNULL(value)) return defaultVal;
        return StringUtil.toFloat(value);
    }

    /**
     * @param request 请求
     * @param name    变量名
     * @return 返回单精度
     */
    public static float getFloat(HttpServletRequest request, String name) {
        return getFloat(request, name, 0);
    }

    /**
     * @param request    请求
     * @param name       名称
     * @param defaultVal 默认
     * @return 变量
     */
    public static double getDouble(HttpServletRequest request, String name, double defaultVal) {
        String value = getString(request, name, true);
        if (StringUtil.isNULL(value)) return defaultVal;
        return StringUtil.toDouble(value);
    }


    /**
     * @param request 请求
     * @param name    名称
     * @return double 类型
     */
    public static double getDouble(HttpServletRequest request, String name) {
        return getDouble(request, name, 0);
    }

    /**
     * @param request 请求
     * @param name    名称
     * @return bool 类型
     */
    public static boolean getBoolean(HttpServletRequest request, String name) {
        String value = getString(request, name, true);
        return StringUtil.toBoolean(value);
    }


    /**
     * 得到字符请求串参数
     *
     * @param request  请求
     * @param name     名称
     * @param checkSql 安全过滤
     * @return 返回
     */
    public static String getString(HttpServletRequest request, String name, String def, boolean checkSql) {
        if (request == null || isRocRequest(request)) return def;
        String s = null;
        try {
            s = request.getParameter(name);
            if (!StringUtil.hasLength(s)) return def;
            if (repairEncode && (repairRequestMethod.equals("*") || StringUtil.indexIgnoreCaseOf(repairRequestMethod, request.getMethod()) != -1)) {
                s = new String(s.getBytes("ISO-8859-1"), Dispatcher.getEncode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (checkSql) {
            return TXWebUtil.getSafeFilter(s,paramMaxLength, SafetyLevel.Middle);
        }
        return s;
    }

    /**
     * @param request  请求
     * @param name     名称
     * @param checkSql 安全过滤
     * @return 得到参数
     */
    public static String getString(HttpServletRequest request, String name, boolean checkSql) {
        return getString(request, name, StringUtil.empty, checkSql);
    }

    /**
     * @param request  请求
     * @param name     变量名称
     * @param checkSql sql安全方式
     * @return 变量数组
     */
    public static String[] getArray(HttpServletRequest request, String name, boolean checkSql) {
        if (request == null || isRocRequest(request)) return null;
        String[] s = null;
        try {
            s = request.getParameterValues(name);
            if (repairEncode && (repairRequestMethod.equals("*") || StringUtil.indexIgnoreCaseOf(repairRequestMethod, request.getMethod()) != -1)) {
                int max = ArrayUtil.getLength(s);
                String[] tempArray = new String[max];
                for (int i = 0; i < max; i++) {
                    String o = (String) Array.get(s, i);
                    if (o != null)
                        tempArray[i] = new String(o.getBytes("ISO-8859-1"), Dispatcher.getEncode());
                }
                s = tempArray;
            }
            if (ArrayUtil.isEmpty(s) && request.getParameter(name) != null) s = new String[]{request.getParameter(name)};
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (s == null) return new String[0];
        if (checkSql) {
            for (int i = 0; i < s.length; i++) {
                s[i] = TXWebUtil.getSafeFilter(s[i],paramMaxLength,2);
            }
        }
        return s;
    }

    /**
     * @param request 请求
     * @param name    名称
     * @return 得到整型数组
     */
    public static Integer[] getIntegerArray(HttpServletRequest request, String name) {
        if (request == null) return null;
        String[] s = getArray(request, name, true);
        if (s == null) return new Integer[0];
        Integer[] result = new Integer[s.length];
        for (int i = 0; i < s.length; i++) {
            result[i] = StringUtil.toInt(s[i], 0);
        }
        return result;
    }

    public static int[] getIntArray(HttpServletRequest request, String name) {
        if (request == null) return null;
        return ArrayUtil.toIntArray(getArray(request, name, true));
    }

    /**
     * @param request 请求
     * @param name    名称
     * @return 得到整型数组
     */
    public static Long[] getLongArray(HttpServletRequest request, String name) {
        if (request == null) return null;
        String[] s = getArray(request, name, true);
        if (s == null) return new Long[0];
        Long[] result = new Long[s.length];
        for (int i = 0; i < s.length; i++) {
            result[i] = StringUtil.toLong(s[i]);
        }
        return result;
    }

    /**
     * @param request 请求
     * @param name    名称
     * @return 得到float数组
     */
    public static float[] getFloatArray(HttpServletRequest request, String name) {
        if (request == null) return null;
        String[] s = getArray(request, name, true);
        if (s == null) return new float[0];
        float[] result = new float[s.length];
        for (int i = 0; i < s.length; i++) {
            result[i] = StringUtil.toFloat(s[i]);
        }
        return result;
    }

    /**
     * 只是为了类型
     * @param request
     * @param name
     * @return
     */
    public static Float[] getFloatObjectArray(HttpServletRequest request, String name) {
        if (request == null) return null;
        String[] s = getArray(request, name, true);
        if (s == null) return new Float[0];
        Float[] result = new Float[s.length];
        for (int i = 0; i < s.length; i++) {
            result[i] = StringUtil.toFloat(s[i]);
        }
        return result;
    }
    /**
     * @param request 请求
     * @param name    名称
     * @return 得到double数组
     */
    public static double[] getDoubleArray(HttpServletRequest request, String name) {
        if (request == null) return null;
        String[] s = getArray(request, name, true);
        if (s == null) return new double[0];
        double[] iResult = new double[s.length];
        for (int i = 0; i < s.length; i++) {
            iResult[i] = StringUtil.toDouble(s[i]);
        }
        return iResult;
    }

    /**
     * 只是为了类型
     * @param request
     * @param name
     * @return
     */
    public static Double[] getDoubleObjectArray(HttpServletRequest request, String name) {
        if (request == null) return null;
        String[] s = getArray(request, name, true);
        if (s == null) return new Double[0];
        Double[] iResult = new Double[s.length];
        for (int i = 0; i < s.length; i++) {
            iResult[i] = StringUtil.toDouble(s[i]);
        }
        return iResult;
    }


    /**
     * 得到日期
     *
     * @param request 请求
     * @param name    变量名称
     * @param date    默认日期
     * @return 参数
     */
    public static Date getDate(HttpServletRequest request, String name, Date date) {
        String sTmp = getString(request, name, true);
        if (StringUtil.isNULL(sTmp)) return date;
        try {
            return StringUtil.toDate(sTmp);
        } catch (Exception e) {
            e.printStackTrace();
            return DateUtil.empty;
        }
    }

    /**
     * 得到日期
     *
     * @param request 请求
     * @param name    变量名称
     * @param format  日期格式
     * @param date    默认日期
     * @return 参数
     */
    public static Date getDate(HttpServletRequest request, String name, String format, Date date) {
        String tmp = getString(request, name, true);
        if (StringUtil.isNULL(tmp)) return date;
        try {
            return StringUtil.toDate(tmp, format);
        } catch (Exception e) {
            return date;
        }
    }

    /**
     * 得到请求的参数名称参数对象
     *
     * @param request 请求
     * @return 参数字符串
     * @throws Exception 你传递的参数不是  request
     */
    public static String[] getParameterNames(HttpServletRequest request) throws Exception {
        if (request == null) return null;
        if (isRocRequest(request)) return null;
        String[] result = null;
        Enumeration enm = request.getParameterNames();
        while (enm.hasMoreElements()) {
            result = ArrayUtil.add(result, (String) enm.nextElement());
        }
        return result;
    }

    /**
     * @param request 请求
     * @param param   参数
     * @return 继承方式重新组合 参数
     * @throws Exception
     */
    static public String toQueryString(HttpServletRequest request, Map<String, String> param) throws Exception {
        if (isRocRequest(request)) return StringUtil.empty;
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            if (!param.containsKey(name))
                param.put(name, getString(request, name, false));
        }
        StringBuilder result = new StringBuilder();
        for (String key : param.keySet()) {
            result.append(key).append("=").append(URLUtil.getURLEncoder(param.get(key), Environment.defaultEncode)).append("&");
        }
        if (result.toString().endsWith("&")) result.setLength(result.length() - 1);
        return result.toString();
    }

    /**
     * 得到请求属性名称列表
     *
     * @param request 请求
     * @return 返回
     * @throws Exception 异常
     */
    public static String[] getAttributeNames(HttpServletRequest request) throws Exception {
        if (request == null) return null;
        String[] result = null;
        Enumeration enm = request.getAttributeNames();
        while (enm.hasMoreElements()) {
            result = ArrayUtil.add(result, (String) enm.nextElement());
        }
        return result;
    }


    /**
     * request 从参数传入Bean对象  MultipartRequest HttpServletRequest 两种情况
     *
     * @param request 请求
     * @param cla     类
     * @return 实体bean
     * @throws Exception 错误
     */
    public static Object getBean(HttpServletRequest request, Class cla,boolean safe) throws Exception {
        Object result = ClassUtil.newInstance(cla.getName());
        if (!isRocRequest(request))
        {
            String[] names = getParameterNames(request);
            if (names == null) return result;
            Method[] methods = ClassUtil.getDeclaredSetMethods(cla);
            for (Method method : methods) {
                String propertyName = method.getName();
                if (StringUtil.isNULL(propertyName) || propertyName.startsWith("get") || propertyName.startsWith("is")) {
                    continue;
                }
                if (propertyName.startsWith("set") && propertyName.length() > 3) {
                    //得到set方法名称
                    propertyName = StringUtil.uncapitalize(propertyName.substring(3, propertyName.length()));
                }
                if (!ArrayUtil.inArray(names, propertyName, true)) {
                    //判断方法是否存在
                    continue;
                }
                Type[] type = method.getParameterTypes();
                if (type != null && type.length > 0) {
                    if (ClassUtil.isArrayType(type[0])) {
                        BeanUtil.setSimpleProperty(result, method.getName(),getArray(request,propertyName,safe));
                    }else
                    if (type[0].equals(java.util.Date.class))
                    {
                        BeanUtil.setSimpleProperty(result, method.getName(),getDate(request,propertyName,new Date()));
                    } else if (type[0].equals(Long.class))
                    {
                        BeanUtil.setSimpleProperty(result, method.getName(),getLong(request,propertyName));
                    }
                    else if (type[0].equals(Integer.class))
                    {
                        BeanUtil.setSimpleProperty(result, method.getName(),getInt(request,propertyName));
                    } else if (type[0].equals(Boolean.class))
                    {
                        BeanUtil.setSimpleProperty(result, method.getName(), getBoolean(request,propertyName));
                    }
                    else {
                        BeanUtil.setSimpleProperty(result, method.getName(),getString(request,propertyName,safe));
                    }
                }
            }
        }
        return result;
    }


    /**
     * @param request 请求
     * @return String 得到浏览器名称
     */
    static public String getBrowser(HttpServletRequest request) {
        String s = request.getHeader(requestUserAgent);
        if (StringUtil.isNULL(s)) return StringUtil.empty;
        s = s.toLowerCase();
        for (String key : browserKeywords.keySet()) {
            if (s.contains(key)) return browserKeywords.get(key);
        }
        return "other";
    }

    /**
     * @param request 请求
     * @return String 得到远程用户操作系统
     */
    static public String getSystem(HttpServletRequest request) {
        String s = request.getHeader(requestUserAgent);
        return getSystem(s);
    }

    static public String getSystem(String agent) {

        if (StringUtil.isNULL(agent)) return StringUtil.empty;
        agent = agent.toLowerCase();
        for (String key : systemKeywords.keySet()) {
            if (agent.contains(key)) return systemKeywords.get(key);
        }
        if (agent.contains("windows")) {
            return "windows";
        }
        return "other";
    }
    /**
     * @param request 请求
     * @return String   得到用户国家信息
     */
    static public String getLocale(HttpServletRequest request) {
        if (request == null) return "zh_CN";
        //从HTTP请求的头信息中获取客户端的语言设置
        String clientLanguage = request.getHeader(requestAcceptLanguage);
        if (StringUtil.isNULL(clientLanguage)) return "zh_CN";
        clientLanguage = clientLanguage.toLowerCase();
        //简体中文浏览器
        if (clientLanguage.contains("zh")) {
            return "zh_CN";
        }        //繁体中文浏览器
        else if (clientLanguage.equalsIgnoreCase("zh-tw")) {
            return "zh_TW";
        }        //日文浏览器
        else if (clientLanguage.equalsIgnoreCase("jp")) {
            return "jp";
        }     //缺省认为是英文浏览器
        else if (clientLanguage.contains("en") || clientLanguage.contains("us")) {
            return "en_US";
        } else {
            return request.getLocalName();
        }
    }

    /**
     * 返回系统支持的语言,不是识别语言
     * @param request
     * @return
     */
    static public String getLanguage(HttpServletRequest request) {
        if (request == null) return "zh";
        //从HTTP请求的头信息中获取客户端的语言设置
        String clientLanguage = request.getHeader(requestAcceptLanguage);
        if (StringUtil.isNULL(clientLanguage)) return "zh";
        clientLanguage = clientLanguage.toLowerCase();
        //简体中文浏览器
        if (clientLanguage.contains("zh")) {
            return "zh";
        }        //繁体中文浏览器
        else if (clientLanguage.equalsIgnoreCase("zh")) {
            return "zh";
        }        //日文浏览器
         //缺省认为是英文浏览器
        else if (clientLanguage.contains("en") || clientLanguage.contains("us")) {
            return "en";
        } else {

            return "zh";
        }
    }
    static public boolean isMobileBrowser(HttpServletRequest request)
    {
        String agent = request.getHeader(requestUserAgent);
        return isMobileBrowser(agent);
    }

    static public boolean isMobileBrowser(String agent)
    {
        if (!StringUtil.hasLength(agent)) return false;
        String agentCheck = agent.trim().toLowerCase();
        if (agentCheck.contains("windows xp") || agentCheck.contains("windows nt") || agentCheck.contains("ubuntu") || agentCheck.contains("center os"))
            return false;
        for (String keyword : mobileKeywords) {
            Pattern p = Pattern.compile(keyword);
            Matcher m = p.matcher(agentCheck);
            boolean find = m.find();
            if (find) {
                return (!agentCheck.contains("ipad")
                        && !agentCheck.contains("ipod")
                        && !agentCheck.contains("macintosh"));
            }
        }
        return false;
    }

    static public boolean checkBrowser(String agent,String browser)
    {
        if (!StringUtil.hasLength(agent)) return false;
        String agentCheck = agent.trim().toLowerCase();
        return agentCheck.contains(browser);
    }


    static public String getNetType(HttpServletRequest request)
    {
        String agent = request.getHeader(requestUserAgent);
        return getNetType(agent);
    }

    static public String getUserAgent(HttpServletRequest request)
    {
        return request.getHeader(requestUserAgent);
    }

    static public String getNetType(String agent)
    {
        if (!StringUtil.hasLength(agent)) return "unknown";
        String agentCheck = agent.trim().toLowerCase();
        if (agentCheck.contains("nettype/"))
        {
            String temp = StringUtil.substringAfter(agentCheck, "nettype/");
            if (temp.length()>5) temp = StringUtil.cut(temp,5,"");
            return temp;
        }
        return "unknown";
    }

    /**
     *
     * @param request 请求
     * @return 排除代理,得到真实的IP地址
     */
    static public String getRemoteAddr(HttpServletRequest request)
    {
        String clientIp = request.getHeader("x-forwarded-for");
        if(StringUtil.isNULL(clientIp) || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if(StringUtil.isNULL(clientIp)|| "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if(StringUtil.isNULL(clientIp)|| "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        if (clientIp.contains(",")) clientIp = StringUtil.substringBefore(clientIp,",");
        return clientIp;
    }

    /**
     * 得到ajax请求的字符串
     * @param request
     * @return
     * @throws IOException
     */
    static public String getReader(HttpServletRequest request) throws IOException {
        ///////////////////读取ajax请求 begin
        BufferedReader buffer = request.getReader();
        StringBuilder call = new StringBuilder();
        String str;
        while ((str = buffer.readLine()) != null) {
            call.append(str);
        }
        buffer.close();
        return call.toString();
    }


}